package com.hulk.dryad.admin.filter;

import com.hulk.dryad.common.component.R;
import com.hulk.dryad.common.constant.SecurityConstants;
import com.hulk.dryad.common.constant.enums.BEC;
import com.hulk.dryad.common.util.WebUtils;
import com.hulk.dryad.persistence.entity.SysUserModel;
import com.hulk.dryad.persistence.service.SysUserService;
import com.warrenstrange.googleauth.GoogleAuthenticator;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @Classname TotpAuthCodeFilter
 * @Description 图形验证码过滤器
 * @Author hulk
 * @Date 2020-07-07 23:02
 */

@Slf4j
@Component
public class TotpAuthCodeFilter extends OncePerRequestFilter implements Ordered {

    private static final String TOTP = "totp";

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

	private static final String UNAME = "username";

	@Autowired
	private SysUserService sysUserService;



    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {

		//要拦截的路径
		if (PATH_MATCHER.match(SecurityConstants.OAUTH_TOKEN_URL, request.getRequestURI())) {
			try {
				int totp = Integer.parseInt(request.getParameter(TOTP));
				String username = request.getParameter(UNAME);
				SysUserModel sysUser = sysUserService.getOneByName(username);
				if (sysUser == null) {
					WebUtils.renderJson(response, R.failed(BEC.E_2015));
				} else {
					GoogleAuthenticator gAuth = new GoogleAuthenticator();
					boolean gAuthFlag = gAuth.authorize(sysUser.getTotp(), totp);
					if (!gAuthFlag) {
						WebUtils.renderJson(response, R.failed(BEC.E_2017));
					}
				}
			} catch (Exception e) {
				WebUtils.renderJson(response, R.failed(BEC.E_2017));
			}
		}

        // 3. 通过放行
        chain.doFilter(request, response);
    }





    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 801;
    }
}
